﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpChess;
using MooneyTool;

namespace TwitterChess
{
    class GameManager
    {
        public delegate void AIMoveMadeHandler(object feedback, AIMoveMadeArgs args);
        public event AIMoveMadeHandler AIMoveMade;

		private List<GameWrapper> games;

		public GameManager()
		{
			games = new List<GameWrapper>();
		}


        public void OnAIMoveMade(object feedback, AIMoveMadeArgs msg)
        {
            try
            {
                if (AIMoveMade != null)
                {
                    AIMoveMade(feedback, msg);
                }
                else
                {
                    throw new Exception("No listeners to AI move.");
                }
            }
            catch (Exception ex)
            {
                Logger.getInstance().Add("Failed to call feedback for received message: " + ex.Message);
            }
        }

		public void NewGame(TwitterOpponent opponent)
		{
			GameWrapper game = new GameWrapper(opponent, this);
			games.Add(game);
		}

        public void GiveUp(String opponent)
		{
			GameWrapper game = FindGame(opponent);
			if (game != null)
			{
				games.Remove(game);
			}
		}

		private GameWrapper FindGame(String opponent)
		{
			foreach (GameWrapper game in games)
			{
				if (game.Opponent.twitterUserName.Equals(opponent))
				{
					return game;
				}
			}
			return null;
		}

        public void ReceiveMessage(object feedback, TweetReceivedEventArgs args)
        {
            if (args.message.Contains("start"))
            {
                NewGame(new TwitterOpponent(args.sender));
            }
            else
            {
                // find game
                GameWrapper Game = this.FindGame(args.sender);

                // parse message
                Move CandidateMove = Game.Opponent.player.MoveFromNotation(args.message);

                // validate move
                if (Move.IsValid(CandidateMove))
                {
                    // make move
                    Game.DoPlayerMove(CandidateMove);
                }
            }
        }
    }
}
